package com.lst.servlet;

import java.io.File;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.lst.base.entity.BaseRequest;
import com.lst.base.entity.BaseResponse;
import com.lst.common.CommCode;
import com.lst.common.CommFun;
import com.lst.dao.ResourcesMapper;
import com.lst.entity.request.ClientReqPara;
import com.lst.entity.response.ClientResPara;
import com.lst.model.MstClient;
import com.lst.model.Resources;
import com.lst.service.MstClientService;
import com.lst.utils.CommonUtils;
import com.lst.utils.DateUtil;
import com.lst.utils.RequestUtils;

/**
 * @ClassName: ClientEditServlet
 * @Description: 个人设置接口
 * @author zhanghl
 * @date 2016年9月30日 下午3:15:16
 *
 */
public class ClientEditServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;

	private MstClientService mstClientService = ctx.getBean(MstClientService.class);

	private ResourcesMapper resourcesMapper = ctx.getBean(ResourcesMapper.class);

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		Date startDate = new Date();

		ClientResPara resPara = new ClientResPara();

		try {
			ClientReqPara reqPara = getReqPara(request);

			if(isCheckField(reqPara,resPara)){
				Integer userid = Integer.valueOf(reqPara.getUserid());
				String nickname = reqPara.getNickname();
				String namecn = reqPara.getNamecn();
				boolean gender = "1".equals(reqPara.getGender());
				String birthday = reqPara.getBirthday();				
				String email = reqPara.getEmail();								
				Integer province = StringUtils.isEmpty(reqPara.getProvince()) ? null : Integer.valueOf(reqPara.getProvince());
				Integer city = StringUtils.isEmpty(reqPara.getCity()) ? null : Integer.valueOf(reqPara.getCity());
				Integer area = StringUtils.isEmpty(reqPara.getArea()) ? null : Integer.valueOf(reqPara.getArea());
				Integer street = StringUtils.isEmpty(reqPara.getStreet()) ? null : Integer.valueOf(reqPara.getStreet());				
				String address = reqPara.getAddress();
				String idcard = reqPara.getIdcard();
				String portrait = reqPara.getPortrait();
				String sign = reqPara.getSign();
				String height = StringUtils.isEmpty(reqPara.getHeight()) ? null : reqPara.getHeight();
				String weight = StringUtils.isEmpty(reqPara.getWeight()) ? null : reqPara.getWeight();

				String _portrait = "";
				if(!StringUtils.isEmpty(portrait)){
					List<String> urls = dealImgs(portrait, startDate, userid);
					_portrait = urls.get(0);
				}

				MstClient mstclient = new MstClient();

				if(!StringUtils.isEmpty(birthday)){	

					Date birth = DateUtil.parse(birthday,DateUtil.ALL_DATE_HORIZONTAL);
					//进行生日与当前日期的判断
					Date  currentDate = DateUtil.getFormatDate(startDate, DateUtil.ALL_DATE_HORIZONTAL);
					int days = (int)((currentDate.getTime()-birth.getTime())/86400000);
					if(days>=0){				
						mstclient.setBirthday(DateUtil.parse(birthday,DateUtil.ALL_DATE_HORIZONTAL));

						mstclient.setId(userid);
						mstclient.setNamecn(namecn);
						mstclient.setNickname(nickname);
						mstclient.setGender(gender);				
						mstclient.setEmail(email);
						mstclient.setProvince(province);
						mstclient.setCity(city);
						mstclient.setArea(area);
						mstclient.setStreet(street);
						mstclient.setAddress(address);
						mstclient.setIdcard(idcard);
						mstclient.setPortrait(_portrait);
						if(!StringUtils.isEmpty(_portrait)){
						mstclient.setReserved11(CommCode.portraitUrl+_portrait);	
						}
						mstclient.setUpdatedate(startDate);
						mstclient.setUpdateuser(userid);
						mstclient.setSign(sign);
						mstclient.setHeight(height);
						mstclient.setWeight(weight);
						
						mstClientService.updateByPrimaryKeySelective(mstclient);

						MstClient mc = mstClientService.selectByPrimaryKey(userid);

						if(!StringUtils.isEmpty(mc.getMobileno())){
							String mobile = mc.getMobileno().replaceAll("(\\d{3})\\d{4}(\\d{4})","$1****$2");
							mc.setMobile(mobile);
							resPara.setMstClient(mc);
						}else{
							resPara.setMstClient(mc);	
						}
						resPara.setCode(CommCode.M_Y000000);
						resPara.setMessage(CommCode.M_Y000001);
					}else{
						resPara.setCode(CommCode.M_A000000);
						resPara.setMessage(CommCode.M_C000022);
					}

				}else{

					mstclient.setId(userid);
					mstclient.setNamecn(namecn);
					mstclient.setNickname(nickname);
					mstclient.setGender(gender);				
					mstclient.setEmail(email);
					mstclient.setProvince(province);
					mstclient.setCity(city);
					mstclient.setArea(area);
					mstclient.setStreet(street);
					mstclient.setAddress(address);
					mstclient.setIdcard(idcard);
					mstclient.setPortrait(_portrait);
					if(!StringUtils.isEmpty(_portrait)){
						mstclient.setReserved11(CommCode.portraitUrl+_portrait);	
					}
					mstclient.setUpdatedate(startDate);
					mstclient.setUpdateuser(userid);
					mstclient.setSign(sign);
					mstclient.setHeight(height);
					mstclient.setWeight(weight);
					
					mstClientService.updateByPrimaryKeySelective(mstclient);

					MstClient mc = mstClientService.selectByPrimaryKey(userid);

					resPara.setCode(CommCode.M_Y000000);
					resPara.setMessage(CommCode.M_Y000001);
					resPara.setMstClient(mc);
				}

			}

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0001);

			logger.error("doPost error: ", e);
		}

		try {
			response.setContentType("application/json;charset=utf-8");
			response.setHeader("pragma", "no-cache");
			response.setHeader("cache-control", "no-cache");

			Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").excludeFieldsWithoutExposeAnnotation().serializeNulls().create();
			String jsonResult = gson.toJson(resPara);

	//		logger.info("ClientEditServlet jsonResult: " + jsonResult);

			PrintWriter out = response.getWriter();
			out.print(jsonResult);
			out.flush();
			out.close();

		//	logger.info("doPost end: " + DateUtil.calLastedTime(startDate));

		} catch (Exception e) {
			resPara.setCode(CommCode.M_A000000);
			resPara.setMessage(CommCode.M_SYS0003);

			logger.error("doPost error: ", e);
		}
	}

	@Override
	public ClientReqPara getReqPara(HttpServletRequest request) {

		ClientReqPara reqPara = null;

		try {
			BaseRequest baseRequest = RequestUtils.getRequestPara(request, new ClientReqPara());

			reqPara = (ClientReqPara) baseRequest.clone();

			String userid = request.getParameter("userid");
			String namecn = request.getParameter("namecn");
			String nickname = request.getParameter("nickname");	
			String gender = request.getParameter("gender");
			String birthday = request.getParameter("birthday");	
			String email = request.getParameter("email");										
			String province = request.getParameter("province");
			String city = request.getParameter("city");
			String area = request.getParameter("area");
			String street = request.getParameter("street");
			String address = request.getParameter("address");
			String idcard = request.getParameter("idcard");
			String portrait = request.getParameter("portrait");			
			String sign = request.getParameter("sign");			
			String mobile = request.getParameter("mobile");
			String height = request.getParameter("height");
			String weight = request.getParameter("weight");

//			logger.info("reqPara userid: " + userid);
//			logger.info("reqPara namecn: " + namecn);
//			logger.info("reqPara nickname: " + nickname);
//			logger.info("reqPara gender: " + gender);	
//			logger.info("reqPara birthday: " + birthday);		
//			logger.info("reqPara email: " + email);					
//			logger.info("reqPara province: " + province);
//			logger.info("reqPara city: " + city);
//			logger.info("reqPara area: " + area);
//			logger.info("reqPara street: " + street);
//			logger.info("reqPara address: " + address);
//			logger.info("reqPara idcard: " + idcard);
//			logger.info("reqPara portrait: " + portrait);			
//			logger.info("reqPara sign: " + sign);			
//			logger.info("reqPara moblie: " + mobile);
//			logger.info("reqPara height: " + height);
//			logger.info("reqPara weight: " + weight);

			reqPara.setUserid(userid);
			reqPara.setNamecn(namecn);
			reqPara.setNickname(nickname);
			reqPara.setGender(gender);
			reqPara.setBirthday(birthday);			
			reqPara.setEmail(email);				
			reqPara.setProvince(province);
			reqPara.setCity(city);
			reqPara.setArea(area);
			reqPara.setStreet(street);				
			reqPara.setAddress(address);
			reqPara.setIdcard(idcard);
			reqPara.setPortrait(portrait);				
			reqPara.setSign(sign);			
			reqPara.setMobile(mobile);
			reqPara.setHeight(height);
			reqPara.setWeight(weight);

		} catch (Exception e) { 
			logger.error("getReqPara error: ", e);
		}

		return reqPara;
	}

	@Override
	public boolean isCheckField(BaseRequest reqPara, BaseResponse resPara) {
		boolean flag = false;

		ClientReqPara registerReqPara = (ClientReqPara) reqPara;
		ClientResPara registerResPara = (ClientResPara) resPara;

		if (StringUtils.isEmpty(registerReqPara.getUserid())) {
			registerResPara.setCode(CommCode.M_A000000);
			registerResPara.setMessage(CommCode.M_P000002);
		} else {
			flag = true;
		}

		return  flag;
	}


	/**
	 * 
	 * @Title: dealImgs
	 * @Description: 处理图片集 
	 * @param @param portrait  
	 * @param @param startDate
	 * @param @param mstClient
	 * @param @return
	 * @param @throws ParseException    设定文件
	 * @return List<String>    返回类型
	 */
	private synchronized List<String> dealImgs(String portrait,Date startDate,Integer userId) throws ParseException{
		//以逗号分分割多张图片
		String [] portraits = portrait.split(",");
		//存放“文件夹 + 图片名称”集
		List<String> urls = new ArrayList<String>();
		//图片资源集
		List<Resources> mstResources = new ArrayList<Resources>();
		//获取时分秒文件夹地址
		String timeAddr = DateUtil.getCurrentTime(DateUtil.ALL_DATE_HORIZONTAL);
		//获取工厂地址
		String facAddr = CommonUtils.getImg_file_path_linux() + timeAddr;

		// 创建工厂文件
		File facFile = new File(facAddr);
		if (!facFile.exists()) {
			facFile.mkdirs();
		}

		String imgName = "";// 图片名称
		String absPath = "";//文件绝对路径
		String relPath = "";//文件相对路径

		// 批量保存图片
		int len = portraits.length;
		for (int i = 0; i < len; i++) {

			imgName = DateUtil
					.getCurrentTime(DateUtil.ALL_DATETIME_STRING_QUEUE)
					+ i;

			absPath = facAddr + "/"+ imgName;

			CommFun.base64StringToImage4One(
					portraits[i], absPath);

			relPath = CommCode.RESOURCE_URL_IMAGE + timeAddr +"/"+imgName + ".jpg";
			urls.add(relPath);

			Resources resource = new Resources();
			resource.setCreatedate(startDate);
			resource.setCreateuser(userId);
			resource.setEnabled(true);
			resource.setExtname(".jpg");
			resource.setIsdeleted(false);
			resource.setResname(imgName);
			resource.setRespath(CommCode.RESOURCE_URL_IMAGE + timeAddr +"/");
			resource.setOrderindex(i);
			resource.setOwnerid(userId);
			resource.setOwnertablename("MST_CLIENT");
			resource.setRestype(CommCode.SYSCODE_REOURCES_TYPE_IMAGE);

			mstResources.add(resource);

			logger.info("decPara absPath : " + absPath + "and the index :" + i);
			logger.info("decPara relPath : " + relPath + "and the index :" + i);
		}

		resourcesMapper.saveList(mstResources);

		return urls;

	}
}
